package com.itheima.manager;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.domain.db.Admin;
import com.itheima.exception.BusinessException;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAdminManager {
    @Reference
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码
     *
     * @return 图形验证码
     */
    public LineCaptcha sendCode() {
        //使用hutool工具包生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50);
        //获取验证码
        String code = lineCaptcha.getCode();
        System.out.println("验证码:" + code);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + code, code, Duration.ofMinutes(5));
        return lineCaptcha;
    }

    /**
     * 登录
     *
     * @param username         用户名
     * @param password         密码
     * @param verificationCode 验证
     * @return
     */
    public String login(String username, String password, String verificationCode) throws BusinessException {
        Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.ADMIN_CODE + verificationCode);
        if (!flag) {
            throw new BusinessException(("验证码输入错误"));
        }
        Admin admin = adminService.findAdminByName(username);
        if (admin == null) {
            throw new BusinessException(("用户名输入错误"));
        }
        //加密密码
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5, admin.getPassword())) {
            throw new BusinessException("密码输入错误");
        }
        //构建token
        Map<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String token = JwtUtil.createToken(map);
        //删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + verificationCode);
        //把token存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, "1", Duration.ofMinutes(30));

        return token;
    }
}
